﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Profari_Heldur_Utan_Um_Prof
{
    public partial class IntroductionText : Form
    {

        #region Static Variables
        public static string introText;
        private static SqlConnection con = new SqlConnection("Data Source=orninn.com;Initial Catalog=Notendaprofanir;Persist Security Info=True;User ID=SonjaNew;Password=Léttjógúrt");
        private static DataTable dt = new DataTable();
        SqlDataReader r = null;
        #endregion

        #region Variables
        int globalGroupsID;
        int globalevaluationID;
        int globalIntroID;
        #endregion

        public IntroductionText()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();            
        }        
        
        private void IntroductionText_Load(object sender, EventArgs e)
        {
            ritxtIntroTextSession.Text = introText;
            
            radSavedIntroduction.Checked = true;
            
            btnSave.Hide();
            btnNext.Hide();

            getIntroductionName();
            if(cmbSavedIntroduction.Items.Count > 0)
                cmbSavedIntroduction.SelectedIndex = 0;
            
            if (CheckBoxes.chkInfoUserAfterValue.Equals(1))
            {
                btnNext.Show();
                btnFinish.Hide();
            }
            else
            {
                btnFinish.Show();
                btnNext.Hide();
            }
            
        }

        #region Buttons
        private void btnNext_Click(object sender, EventArgs e)
        {
            /*if (ritxtIntroTextSession.Text == "")
            {
                MessageBox.Show("Please put in some text");
                lblWarningText.Show();
                lblWarningText.Text = "Please type some text that are marked with red star";
            }
            else */
            if (CheckBoxes.chkInfoUserAfterValue == 1)
            {
                if (CheckBoxes.radEssayValue == 1)
                {
                    System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenCreateEssay));
                    testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                    testerInterface.Start();
                    this.Close();
                }
                else if (CheckBoxes.radSurveyValue == 1)
                {
                    System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenCreateSurvey));
                    testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                    testerInterface.Start();
                    this.Close();
                }
            }
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            if (radNewIntroduction.Checked && (ritxtIntroTextSession.Text == "" || txtNewIntroduction.Text == ""))
                MessageBox.Show("Please fill in the necessary data");
            else
            {
                if (CreateTask.globalGroupID == 0)
                {
                    insertGroups();
                    globalGroupsID = getGroupsID();
                }
                else
                    globalGroupsID = CreateTask.globalGroupID;
                insertEvaluation();
                insertIntroductionText();
                globalevaluationID = getEvaluationID();
                insertGroupEvaluations(globalGroupsID, globalevaluationID);
                insertTasks();
                getTaskID();
                globalIntroID = getIntroID();
                insertEvaluationTask();
                getCheckBoxes();
                insertCheckBoxInfo();
                System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTesterInterface));
                testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                testerInterface.Start();
                CreateTask.taskList.Clear();
                CreateTask.TaskID.Clear();
                this.Close();
            }
        }
        private void btnBack_Click(object sender, EventArgs e)
        {
            //User is moved to the window where he can choose if he wants to put some extra in his project, like introduction
            System.Threading.Thread checkBoxes = new System.Threading.Thread(new System.Threading.ThreadStart(OpenCheckBoxes));
            checkBoxes.SetApartmentState(System.Threading.ApartmentState.STA);
            checkBoxes.Start();
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //If user wants to quit the project he is moved to the first window
            DialogResult cancelProject = MessageBox.Show("Are you sure you want to stop making new project?", "Quit", MessageBoxButtons.YesNo);
            if (cancelProject == DialogResult.Yes)
            {
                System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTesterInterface));
                testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                testerInterface.Start();
                this.Close();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (radNewIntroduction.Checked && (ritxtIntroTextSession.Text == "" || txtNewIntroduction.Text == ""))
                MessageBox.Show("Please fill in the necessary data");
            else
            {
                string temp = txtNewIntroduction.Text;
                insertIntroBeforeEvaluatin();
                cmbSavedIntroduction.Items.Clear();
                getIntroductionName();
                radSavedIntroduction.Checked = true;
                cmbSavedIntroduction.SelectedIndex = cmbSavedIntroduction.FindStringExact(temp);
            }       
            /*
             * ritxtIntro = ritxtIntroTextSession.Text;
             *con.Open();
             *SqlCommand cmd = new SqlCommand("Insert INTO TAFLA(nafn á  Introduction textanum í töflunni)" + "VALUES(@ritxtIntro)", con);
             int restul = cmd.ExecuteNonQuery();
             * if(result > 0)
             * {
             *      MessageBox.Show("Introduction text has been saved");
             * }
             * con.Close();
             */
        }
        #endregion

        //Gets the value from the static variables in the form CheckBoxes
        public void getCheckBoxes()
        {
            CheckBoxes.chkIntroSessionValue.GetHashCode();
            CheckBoxes.chkInfoUserBeforeValue.GetHashCode();
            CheckBoxes.chkNameValue.GetHashCode();
            CheckBoxes.chkSsnValue.GetHashCode();
            CheckBoxes.chkMobileValue.GetHashCode();
            CheckBoxes.chkAddressValue.GetHashCode();
            CheckBoxes.chkGenderValue.GetHashCode();
            CheckBoxes.chkBirthYearValue.GetHashCode();
            CheckBoxes.chkOtherValue.GetHashCode();
            CheckBoxes.chkInfoUserAfterValue.GetHashCode();
            if (CheckBoxes.radEssayValue == 1)
            {
                CheckBoxes.radEssayValue = 1;
                CheckBoxes.radSurveyValue = 0;
            }
            if (CheckBoxes.radSurveyValue == 1)
            {
                CheckBoxes.radSurveyValue = 1;
                CheckBoxes.radEssayValue = 0;
            }
            CheckBoxes.txtEmailValue.ToString();
            CheckBoxes.chkEmailValue.GetHashCode();
        }

        //The function of the form is decided from the radion button that is check
        #region CheckBoxes/RadioButtons changes
        private void radSavedIntroduction_CheckedChanged(object sender, EventArgs e)
        {
            if (radSavedIntroduction.Checked == true)
            {
                ritxtIntroTextSession.ReadOnly = true;
                cmbSavedIntroduction.Show();
                txtNewIntroduction.Hide();
                getIntroductionText();
                btnSave.Hide();
            }
        }

        private void radNewIntroduction_CheckedChanged(object sender, EventArgs e)
        {
            if (radNewIntroduction.Checked == true)
            {
                ritxtIntroTextSession.ReadOnly = false;
                cmbSavedIntroduction.Hide();
                txtNewIntroduction.Show();
                btnSave.Show();
                ritxtIntroTextSession.Clear();
                txtNewIntroduction.Clear();
            }
        }
        #endregion

        //Displays values from database in a dropdown list
        private void cmbSavedIntroduction_SelectedIndexChanged(object sender, EventArgs e)
        {
            getIntroductionText();
        }

        #region SQL commands
        private void insertGroups()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO Groups(name) values('" + CreateTask.txtCreateGroupNameValue + "')", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertEvaluation()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO Evaluation(name,url,email) values(@txtname, @txturl, @txtemail)", con);
                cmd.Parameters.AddWithValue("@txtname", (CreateTask.txtEvaluationNameValue == "" ? DBNull.Value : (object)CreateTask.txtEvaluationNameValue));
                cmd.Parameters.AddWithValue("@txturl", (CreateTask.txtWebPageValue == "" ? DBNull.Value : (object)CreateTask.txtWebPageValue));
                cmd.Parameters.AddWithValue("@txtemail", (CheckBoxes.txtEmailValue.ToString() == "" ? DBNull.Value : (object)CheckBoxes.txtEmailValue.ToString()));
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private int getGroupsID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select top 1 id from Groups order by id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    return r.GetInt32(0);
                }

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
            return 0;
        }

        private int getEvaluationID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select top 1 id from Evaluation order by id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    return r.GetInt32(0);
                }

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
            return 0;
        }

        private void insertGroupEvaluations(int GroupsID, int EvaluationID)
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO GroupEvaluations(GroupsID,evaluationID) values('" + GroupsID + "','" + EvaluationID + "')", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertIntroductionText()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO task(descript) VALUES(@descript)", con);
                cmd.Parameters.AddWithValue("@descript", ritxtIntroTextSession.Text);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertTasks()
        {

            foreach (CreateTask.Tasks TaskObj in CreateTask.taskList)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO task(name, taskDescription, scenariosDescription) VALUES(@txtname, @txtTaskDescript, @txtScenario)", con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();

                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());

                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void getTaskID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select top " + CreateTask.taskList.Count + " id from task order by id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (!r.IsDBNull(0))
                    {
                        CreateTask.TaskID.Add(r.GetInt32(0));
                    }

                }

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private int getIntroID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT id FROM IntroBeforeEvaluation where name ='" + (string)cmbSavedIntroduction.SelectedItem + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    return r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
            return 0;
        }

        private void insertEvaluationTask()
        {
            foreach (int id in CreateTask.TaskID)
            {
                try
                {
               //     MessageBox.Show("EID: " + globalevaluationID + " TID: " + id + " Intro: " + globalIntroID);
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO EvaluationTask(evaluationID, taskID, introBeforeEvaluationID) values('" + globalevaluationID + "','" + id + "','" + globalIntroID +"')", con);
                    cmd.ExecuteNonQuery();

                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());

                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void insertCheckBoxInfo()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO checkBoxInfo(groupsID, evaluationID, introBeforeEvaluationID, name, ssn,mobile,addres,gender,birthYear,other,userFeedback)" +
                                                "values('" + globalGroupsID + "','" + globalevaluationID + "','" + CheckBoxes.chkIntroSessionValue + "','" + CheckBoxes.chkNameValue +
                                                "','" + CheckBoxes.chkSsnValue + "','" + CheckBoxes.chkMobileValue + "','" + CheckBoxes.chkAddressValue + "','" + CheckBoxes.chkGenderValue +
                                                "','" + CheckBoxes.chkBirthYearValue + "','" + CheckBoxes.chkOtherValue + "','" + CheckBoxes.chkInfoUserAfterValue + "')", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void getIntroductionName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT name FROM IntroBeforeEvaluation", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    cmbSavedIntroduction.Items.Add(r["Name"]);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        private void getIntroductionText()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT introDescription FROM IntroBeforeEvaluation where name ='" + (string)cmbSavedIntroduction.SelectedItem+"'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    ritxtIntroTextSession.Text = r.GetString(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        private void insertIntroBeforeEvaluatin()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO IntroBeforeEvaluation(name,introDescription) Values(@name, @introDescript)", con);
                cmd.Parameters.AddWithValue("@name", txtNewIntroduction.Text == "" ? DBNull.Value : (object)txtNewIntroduction.Text);
                cmd.Parameters.AddWithValue("@introDescript", ritxtIntroTextSession.Text == "" ? DBNull.Value : (object)ritxtIntroTextSession.Text);
                
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateEvaluationTask(int introID)
        {
            foreach( int taskID in CreateTask.TaskID)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("UPDATE EvaluationTask SET introBeforeEvaluationID =" + introID + " where evaluationID="+globalevaluationID+ " AND taskID="+taskID, con);
                    r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        cmbSavedIntroduction.Items.Add(r["Name"]);
                    }
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                        con.Close();
                }
            }
        }
        #endregion

    
        //The Open forms functions makes it able to move between forms and close the first form when the second one is opened
        #region OpenForms

        public static void OpenCheckBoxes()
        {
            Application.Run(new CheckBoxes());
        }

        public void OpenTesterInterface()
        {
            Application.Run(new TesterInterface());
        }

        public static void OpenCreateEssay()
        {
            Application.Run(new CreateEssay());
        }

        public static void OpenCreateSurvey()
        {
            Application.Run(new CreateSurvey());
        }
        #endregion

    }
}
